package com.yaoayao.mall.activity.controller;

import com.yaoayao.mall.activity.redis.CacheHelper;
import com.yaoayao.mall.activity.service.ActivityService;
import com.yaoayao.mall.activity.utils.DateUtil;
import com.yaoayao.mall.common.constant.RedisConst;
import com.yaoayao.mall.common.result.Result;
import com.yaoayao.mall.common.result.ResultCodeEnum;
import com.yaoayao.mall.common.util.AuthContextHolder;
import com.yaoayao.mall.common.util.MD5;
import com.yaoayao.mall.model.activity.OrderRecode;
import com.yaoayao.mall.model.activity.SeckillGoods;
import com.yaoayao.mall.model.activity.UserRecode;
import com.yaoayao.mall.model.order.OrderDetail;
import com.yaoayao.mall.model.order.OrderInfo;
import com.yaoayao.mall.model.user.UserAddress;
import com.yaoayao.mall.order.client.OrderFeignClient;
import com.yaoayao.mall.rabbit.constant.MqConst;
import com.yaoayao.mall.rabbit.service.RabbitService;
import com.yaoayao.mall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: Peiyao
 * @Date: 2024/04/23 18:45
 */

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillApiController {
    @Autowired
    private ActivityService activityService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserFeignClient userFeignClient;

    public static final String salt = "qwereafg";

    //获取抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSecKillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        SeckillGoods seckillGoods = activityService.findBySkuId(skuId);
        //1.活动时间
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();
        Date curTime = Calendar.getInstance().getTime();

        if (DateUtil.dateCompare(startTime,curTime)&& !DateUtil.dateCompare(endTime,curTime)){
            //抢购吗
            String encrypt = MD5.encrypt(salt + userId);
            return Result.ok(encrypt);
        }else {
            return Result.fail().message("不在活动范围内");
        }
        //2:审核通过
        //3:剩余库存大于0
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result secKillOrder(@PathVariable Long skuId,String skuIdStr,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //        1、校验抢购码
        String encrypt = MD5.encrypt(salt + userId);
        if (!encrypt.equals(skuIdStr)){
            return Result.fail().message("校验失败");
        }
        //        2、校验状态位
        Object status = CacheHelper.get(skuId.toString());
        if (!"1".equals(status)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
        //        3、发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setSkuId(skuId);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,userRecode);
        return Result.ok();
    }

    //开始检查
//        Redis
//    1、商品信息
//    2、库存信息
//    3、用户来过没
//    4、抢购资格
//    5、用户下的单
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1.检验5
        Object o = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
        if (o!=null){
            return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
        }
        //2.检查四
        Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
        if (o1!=null){
            return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
        }
        //3.检查 状态位
        Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId);
        if (o2==null){
            //用户没来过
            Object o3 = CacheHelper.get(skuId.toString());
            if ("1".equals(o3)){
                return Result.build(null,ResultCodeEnum.SECKILL_RUN);
            }
        }
        return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
    }

    /**
     * 秒杀确认订单
     * @param request
     * @return
     */
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request) {

        String userId = AuthContextHolder.getUserId(request);

        List<UserAddress> userAddressList = userFeignClient.userAddressList();

        OrderRecode orderRecode = (OrderRecode) redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS
                + userId);
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
        // 声明一个集合来存储订单明细
        ArrayList<OrderDetail> detailArrayList = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        // 添加到集合
        detailArrayList.add(orderDetail);

        Map<String, Object> result = new HashMap<>();
        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", detailArrayList);
        // 保存总金额
        result.put("totalAmount", orderDetail.getOrderPrice());
        result.put("totalNum", orderDetail.getSkuNum());
        return Result.ok(result);
    }

    @Autowired
    private OrderFeignClient orderFeignClient;

    /**
     * 秒杀提交订单
     *
     * @param orderInfo
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);

        OrderRecode orderRecode = (OrderRecode) redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS
                + userId);
        if (null == orderRecode) {
            return Result.fail().message("非法操作");
        }

        orderInfo.setUserId(Long.parseLong(userId));

        Long orderId = orderFeignClient.submitOrder(orderInfo);
        if (null == orderId) {
            return Result.fail().message("下单失败，请重新操作");
        }

        //删除下单信息
        redisTemplate.delete(RedisConst.SECKILL_ORDERS + userId);
        //下单记录
        redisTemplate.delete(RedisConst.SECKILL_ORDERS_USERS + userId);

        return Result.ok(orderId);
    }
}
